import com.alibaba.fastjson.JSON;
import lombok.Data;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;


public class Shuo {
    public static String template1 = "" +
            "\"nodejs\";\n" +
            "const { device } = require('device')\n" +
            "const { delay } = require('lang');\n" +
            "const { performGestures, StrokeDescription, gestures } = require('accessibility');\n" +
            "var dw = device.displayMetrics.heightPixels\n" +
            "var dh = device.displayMetrics.widthPixels\n" +
            "var h1 = (dw) / 10\n" +
            "var bh = (dw) / 7.2\n" +
            "var bh2 = (bh) * 0.28\n" +
            "var ys = h1 + bh / 2\n" +
            "var aa = bh + bh2\n" +
            "var xs = (dh - bh * 5 - bh2 * 4) / 2\n" +
            "var gg = [key]\n" +
            "var sl = [sleep]\n" +
            "async function main() {\n" +
            "    for (let i = 0; i < gg.length; i++) {\n" +
            "        await delay(sl[i]);\n" +
            "        if (gg[i].length !== 0) {\n" +
            "            if (gg[i].length === 1) {\n" +
            "                performGestures([new StrokeDescription(\n" +
            "                    gg[i], 1, 0\n" +
            "                )])\n" +
            "            }\n" +
            "            else {\n" +
            "                var temp = []\n" +
            "                for (let index = 0; index < gg[i].length; index++) {\n" +
            "                    temp.push(new StrokeDescription(\n" +
            "                        [gg[i][index]], 1, 0\n" +
            "                    ))\n" +
            "                }\n" +
            "                performGestures(temp)\n" +
            "            }\n" +
            "        }\n" +
            "    }\n" +
            "}\n" +
            "main();";

    @Data
    public static class SongNotesDTO {
        private Integer time;
        private String key;
    }

    @Data
    public static class YPBean {

        private String name;
        private String author;
        private String arrangedBy;
        private String transcribedBy;
        private String permission;
        private Integer bpm;
        private Integer bitsPerPage;
        private Integer pitchLevel;
        private LinkedList<SongNotesDTO> songNotes;
    }


    @Data
    public static class YPBeanList {

        private String name;
        private String author;
        private String arrangedBy;
        private String transcribedBy;
        private String permission;
        private Integer bpm;
        private Integer bitsPerPage;
        private Integer pitchLevel;
        private List<List<SongNotesDTO>> songNotes;
    }


    public static Map<String, Integer[]> key = new HashMap<String, Integer[]>() {{

        //琴键点位，可自行开启触控显示定位每个琴键
        /**
         * 1Key0     1Key1    1Key2    1Key3    1Key4
         * 1Key5     1Key6    1Key7    1Key8    1Key9
         * 1Key10    1Key11   1Key12   1Key13   1Key14
         */

        for (int i = 0; i < 15; i++) {
            put("1Key" + i, new Integer[]{Integer.valueOf((int) Math.ceil((i / 5)+1)), (i%5)+1});
        }
        System.out.println(JSON.toJSONString(this));
    }};


    public static void main(String[] args) throws IOException {
        run(
                "/Users/satan/git-project/guangyu4jautojs/src/main/java/yp/义勇军进行曲.txt",
                "/Users/satan/git-project/guangyu4jautojs/src/main/java/output/义勇军进行曲.js"
        );
    }
    public static void run(String filePath,String outFilePath) throws IOException {

        for (int ii = 0; ii < 1; ii++) {
            String sb = readFile(filePath).replaceAll("[0-9]K", "1K");
            String template = template1;
            List<YPBean> ypBeans = JSON.parseArray(sb, YPBean.class);
            if (ypBeans == null || ypBeans.size() == 0) return;
            StringBuilder sbOut = new StringBuilder("[");
            LinkedList<SongNotesDTO> songNotesTemp = ypBeans.get(0).getSongNotes();
            LinkedHashMap<Integer, List<SongNotesDTO>> collect = new LinkedHashMap<Integer, List<SongNotesDTO>>() {{
                Map<Integer, List<SongNotesDTO>> collect1 = songNotesTemp.stream().collect(Collectors.groupingBy(songNotesDTO -> songNotesDTO.getTime()));
                List<Integer> integers = collect1.keySet().stream().sorted().collect(Collectors.toList());
                for (int i = 0; i < integers.size(); i++) {
                    put(integers.get(i), collect1.get(integers.get(i)));
                }
            }};
            LinkedList<List<SongNotesDTO>> songNotes = new LinkedList<>(collect.values());
            for (int i = 0; i < songNotes.size(); i++) {
                List<SongNotesDTO> items = songNotes.get(i);
                if (items.size() == 1) {
                    //单键
                    SongNotesDTO item = items.get(0);
                    String val = "{x:"+"xs+"+(key.get(item.getKey())[1])+"*aa-aa+bh/2"+",y:"+(key.get(item.getKey())[0])+"*aa-aa+ys"+"" + "},";
                    sbOut.append("[");
                    sbOut.append(val);
                    sbOut.append("],");
                } else {
                    sbOut.append("[");
                    //多键
                    for (int i1 = 0; i1 < items.size(); i1++) {
                        SongNotesDTO item = items.get(i1);
                        String val = "{x:"+"xs+"+(key.get(item.getKey())[1])+"*aa-aa+bh/2"+",y:"+(key.get(item.getKey())[0])+"*aa-aa+ys"+"" + "},";
                        sbOut.append(val);
                    }
                    sbOut.append("],");
                }
            }
            sbOut.append("]");

            LinkedList<Integer> sl = new LinkedList<>(collect.keySet());
            LinkedList<Integer> slEnd = new LinkedList<Integer>() {{
                for (int i = 0; i < sl.size(); i++) {
                    Integer item = sl.get(i);
                    if (i == 0) {
                        add(item);
                    } else {
                        add(item - sl.get(i - 1));
                    }
                }
            }};
            template = template.replaceAll("\\[key\\]", sbOut.toString())
                    .replaceAll("\\[sleep\\]", JSON.toJSONString(slEnd));
            writeStringToFile(template, outFilePath);
            System.out.println(template);
            System.out.println("操作完成");
        }
    }

    //读文件
    public static String readFile(String filePath) throws IOException {
        //名称
        File file = new File(filePath);
        if (!file.exists()) return null;
        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(new FileReader(file));
        String s = null;
        while ((s = br.readLine()) != null) {
            s = new String(s.getBytes());
            sb.append(s).append("\n");
        }
        br.close();
        return sb.toString();
    }

    //写字符串到文件
    public static String writeStringToFile(String data, String filePath) throws IOException {
        //名称
        File file = new File(filePath);
        if (!file.exists()) file.createNewFile();
        StringBuilder sb = new StringBuilder();
        BufferedWriter br = new BufferedWriter(new FileWriter(file));
        String s = null;
        br.write(data);
        br.close();
        return sb.toString();
    }
}
